package com.gxgy.app.service.imp;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxgy.common.exception.ServiceException;
import com.gxgy.common.utils.StringUtils;
import com.gxgy.app.doman.po.User;
import com.gxgy.app.doman.vo.UserVo;
import com.gxgy.app.mapper.UserMapper;
import com.gxgy.app.service.UserService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service("appUserServiceImpl")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public boolean registerUser(User user) {
        // 先查询用户是不是已经存在
        // 构造查询条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getUsername, user.getUsername());
        User us = this.getOne(wrapper);
        if (StringUtils.isNotNull(us)) {
            // 用户已经存在了
            throw new ServiceException("用户已经存在");
        }
        // 用户存在，插入数据库

        // 先计算bim值 身高是厘米，体重是公斤
        setBimAndRemake(user);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        this.save(user);
        return true;
    }

    @Override
    public UserVo login(User user) {
        // 查询用户是否存在
        // 构造查询条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getUsername, user.getUsername())
                .eq(User::getPassword, user.getPassword());
        User us = this.getOne(wrapper);
        if (StringUtils.isNull(us)) {
            // 用户不存在
            throw new ServiceException("账户或者密码错误");
        }
        // 构建返回对象
        UserVo userVo = new UserVo();
        // 拷贝对象
        BeanUtil.copyProperties(us, userVo);
        return userVo;
    }

    @Override
    public User updateUser(User user) {
        // 检查用户是否存在
        User byId = this.getById(user.getId());
        if (StringUtils.isNull(byId)) {
            // 用户不存在
            throw new ServiceException("用户不存在");
        }
        // 用户修改了信息，重新计算bim和评价
        setBimAndRemake(user);
        // 调用方法修改
        boolean updated = this.saveOrUpdate(user);
        if(!updated){
            throw new ServiceException("修改失败");
        }
        return user;
    }

    private void setBimAndRemake(User user) {
        Double bim = user.getWeight() / Math.pow(user.getHeight() / 100, 2);
        user.setBim(bim);
        if(bim < 18.5){
            user.setBimRemake("过轻");
            user.setBimClassify(0L);
        }else if(bim < 24){
            user.setBimRemake("正常");
            user.setBimClassify(1L);
        }else if(bim < 28){
            user.setBimRemake("超重");
            user.setBimClassify(2L);
        }else {
            user.setBimRemake("肥胖");
            user.setBimClassify(3L);
        }
    }
}
